package com.wxy.library.controller;



import com.wxy.library.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${book.path}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suddix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suddix;
        File dir = new File(basePath);
        if (!dir.exists()) {
            //目录不存在需要创建
            dir.mkdir();
        }
        try {
            file.transferTo(new File(basePath + fileName).getAbsoluteFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public R<String> download(String name) {
        if(name.equals(""))
            return null;
        byte[]data = null;
        try {
            //输入流
            FileInputStream in = new FileInputStream(new File(basePath + name));
            data = new byte[in.available()];
            in.read(data);
            in.close();
            //输出流，通过输出流写回浏览器
            //ServletOutputStream outputStream = response.getOutputStream();
            //            int len = 0;
            //            byte[] bytes = new byte[1024];
            //            while ((len = fileInputStream.read(bytes)) != -1) {
            //
            ////                outputStream.write(bytes, 0, len);
            ////                outputStream.flush();
            //            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return R.success(encoder.encode(data));
    }
}
